/*
 * Copyright 2021 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package org.edgegallery.developer.service.recource.vm.impl;

import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.edgegallery.developer.common.Consts;
import org.edgegallery.developer.common.ResponseConsts;
import org.edgegallery.developer.exception.DataBaseException;
import org.edgegallery.developer.filter.security.AccessUserUtil;
import org.edgegallery.developer.mapper.resource.vm.FlavorMapper;
import org.edgegallery.developer.model.resource.vm.Flavor;
import org.edgegallery.developer.service.recource.vm.FlavorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("flavorService")
public class FlavorServiceImpl implements FlavorService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FlavorServiceImpl.class);

    @Autowired
    FlavorMapper flavorMapper;

    @Override
    public List<Flavor> getAllFlavors() {
        if (isAdminUser()) {
            return flavorMapper.getAllFlavors();
        } else {
            return flavorMapper.getFlavorsByUserId(AccessUserUtil.getUserId());
        }
    }

    @Override
    public Flavor getFlavorById(String flavorId) {
        return flavorMapper.getFlavorById(flavorId);
    }

    @Override
    public Flavor createFlavor(Flavor flavor) {
        flavorMapper.getAllFlavors().forEach(item -> {
            if (item.getName().equals(flavor.getName()) && StringUtils.isNotBlank(item.getUserId()) && item.getUserId()
                .equals(flavor.getUserId())) {
                LOGGER.error("exist same data.");
                throw new DataBaseException("exist same data.", ResponseConsts.RET_CREATE_DATA_FAIL);
            }
        });
        flavor.setId(UUID.randomUUID().toString());
        int res = flavorMapper.createFlavor(flavor);
        if (res < 1) {
            LOGGER.error("Create flavor in db error.");
            throw new DataBaseException("Create flavor in db error.", ResponseConsts.RET_CREATE_DATA_FAIL);
        }
        return flavor;
    }

    @Override
    public Boolean deleteFlavorById(String flavorId, String userId) {
        int res = 0;
        if (isAdminUser()) {
            res = flavorMapper.deleteFlavorById(flavorId, null);
        } else {
            res = flavorMapper.deleteFlavorById(flavorId, userId);
        }
        if (res == 0) {
            LOGGER.error("delete flavor in db error.");
            throw new DataBaseException("delete flavor in db error.", ResponseConsts.RET_CREATE_DATA_FAIL);
        }
        return true;
    }

    @Override
    public Boolean modifyFlavorById(String flavorId, Flavor flavor) {
        Flavor queryRes = flavorMapper.getFlavorById(flavorId);
        if (queryRes == null) {
            LOGGER.error("query flavor is null.");
            throw new DataBaseException("query flavor is null.", ResponseConsts.RET_QUERY_DATA_EMPTY);
        }
        flavor.setId(flavorId);
        flavorMapper.getFlavors(flavorId).forEach(item -> {
            if (item.getName().equals(flavor.getName()) && StringUtils.isNotBlank(item.getUserId()) && item.getUserId()
                .equals(flavor.getUserId())) {
                LOGGER.error("exist same data.");
                throw new DataBaseException("exist same data.", ResponseConsts.RET_CREATE_DATA_FAIL);
            }
        });
        int res = flavorMapper.updateFlavorById(flavor);
        if (res < 1) {
            LOGGER.error("modify flavor in db error.");
            throw new DataBaseException("modify flavor in db error.", ResponseConsts.RET_UPDATE_DATA_FAIL);
        }
        return true;
    }

    private boolean isAdminUser() {
        String currUserAuth = AccessUserUtil.getUser().getUserAuth();
        return !StringUtils.isEmpty(currUserAuth) && currUserAuth.contains(Consts.ROLE_DEVELOPER_ADMIN);
    }
}
